package frontend.pages.worklog.closemonth;

import backend.model.other.MonthState;
import backend.service.other.MonthStateService;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.worklog.MonthStateUIModel;
import frontend.pages.base.BaseWebPage;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.wicketstuff.annotation.mount.MountPath;

import java.util.Calendar;

import static shared.other.UserRolesDefinition.ADMIN_ROLE_KEY;

@MountPath("monthState")
@AuthorizeInstantiation(value = {ADMIN_ROLE_KEY})
public class MonthStatePage extends BaseWebPage {

    public static final String HELP_PANEL_TEXT = "contextualHelp.monthStatePage.text";

    private MonthStateUIModel monthModel;

    public MonthStatePage() {
        super(HELP_PANEL_TEXT);
        initMonthModel();
        initComponents();
    }

    private void initMonthModel() {
        Calendar calendar = Calendar.getInstance();

        MonthStateService service = TimeTrackingWebApplication.getService(MonthStateService.class);
        MonthState dbMonthState = service.findMonthStateByDate(calendar.getTime());
        if (dbMonthState != null) {
            monthModel = new MonthStateUIModel(dbMonthState);
        } else {
            int currentMonthZeroBased = calendar.get(Calendar.MONTH);
            int currentYear = calendar.get(Calendar.YEAR);
            monthModel = new MonthStateUIModel(currentMonthZeroBased + 1, currentYear);
        }
    }

    private void initComponents() {
        buildWorkLogFormContainer();
    }

    private void buildWorkLogFormContainer() {
        setOutputMarkupId(true);
        setOutputMarkupPlaceholderTag(true);
        add(new MonthStateForm("form", monthModel));
    }
}
